package com.jnu.student.myfirstapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class BookDetailsActivity extends AppCompatActivity {
    int position = -1, imageID;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_book);

        // 处理传来的数据
        Intent intent_incoming = getIntent();

        if (intent_incoming != null) {
            // 从Intent中获取传递的数据（有name则"修改"，没有则"添加"）
            String name = intent_incoming.getStringExtra("name");
            if (null != name) {
                position = intent_incoming.getIntExtra("position",-1);
                EditText editTextItemName= findViewById(R.id.editTextText);
                editTextItemName.setText(name);
            }
            else {
                imageID = intent_incoming.getIntExtra("imageId", 0);
            }
        }

        // 数据传出以及切换activity
        Button buttonOK = findViewById(R.id.button_add_ok);
        buttonOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent();
                EditText editTextItemName= findViewById(R.id.editTextText);     // 获取数据
                intent.putExtra("name", editTextItemName.getText().toString());    // 传回数据
                intent.putExtra("imageId", imageID);
                if (position != -1)
                    intent.putExtra("position", position);
                setResult(Activity.RESULT_OK, intent);
                BookDetailsActivity.this.finish();
            }
        });
        Button buttonCancel = findViewById(R.id.button_add_cancel);
        buttonCancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                setResult(Activity.RESULT_CANCELED, new Intent());
                BookDetailsActivity.this.finish();
            }
        });
    }
}